package cn.czu.wyw.intercept;

import cn.czu.wyw.utils.CommonJsonResult;
import cn.czu.wyw.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @Author wyw
 * @Description
 * @Date 2022/1/14 17:05
 * @Version 1.0
 */
@Slf4j
public class UserTokenInterceptor  implements HandlerInterceptor {
    /**
     * 拦截请求，在访问之前
     * @param request
     * @param response
     * @param handler
     * @return bool (true/false);false :请求被拦截，被驳回验证出现问题
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("UserTokenInterceptor  pre, HttpServletRequest：{}",request.getRequestURI());
        returnErrorResponse(response,CommonJsonResult.errorMsg("已被拦截"));
        return false;
    }
    /**
     * 拦截请求，在访问之后，视图渲染之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("UserTokenInterceptor  post, HttpServletRequest：{}",request.getRequestURI());
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 拦截请求，在视图渲染之后
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("UserTokenInterceptor  after, HttpServletRequest：{}",request.getRequestURI());
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
    private void returnErrorResponse(HttpServletResponse response, CommonJsonResult commonJsonResult){
        OutputStream outputStream = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            outputStream = response.getOutputStream();
            outputStream.write(JsonUtils.objectToJson(commonJsonResult).getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (outputStream !=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
